package com.dpltoy.app;

import android.content.Context;
import java.io.File;
import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import org.json.JSONObject;

public class ClearCacheModule extends UniModule {

    @UniJSMethod(uiThread = false)
    public void getTotalCacheSize(UniJSCallback callback) {
        Context context = mUniSDKInstance.getContext();
        long size = getFolderSize(context.getCacheDir());
        File externalCache = context.getExternalCacheDir();
        if (externalCache != null) {
            size += getFolderSize(externalCache);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("size", size);
        } catch (Exception e) {}
        if (callback != null) callback.invoke(result);
    }

    @UniJSMethod(uiThread = false)
    public void clearCache(UniJSCallback callback) {
        Context context = mUniSDKInstance.getContext();
        boolean success = deleteDir(context.getCacheDir());
        File externalCache = context.getExternalCacheDir();
        if (externalCache != null) {
            success = success && deleteDir(externalCache);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("success", success);
        } catch (Exception e) {}
        if (callback != null) callback.invoke(result);
    }

    private long getFolderSize(File dir) {
        long size = 0;
        if (dir != null && dir.exists()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        size += getFolderSize(file);
                    } else {
                        size += file.length();
                    }
                }
            }
        }
        return size;
    }

    private boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) return false;
            }
        }
        return dir.delete() || !dir.exists();
    }
} 